#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

void CountSort(int* a, int n)
{
	int min = 0, max = 0;
	for (int i = 0; i < n; i++)
	{
		if (i == 0)
		{
			min = a[i];
			max = a[i];
		}
		else
		{
			if (a[i] > max)
				max = a[i];
			if (a[i] < min)
				min = a[i];
		}
	}
	int* tmp = (int*)malloc(sizeof(int) * (max - min+1));
	for (int i = 0; i < max - min + 1; i++)
	{
		tmp[i] = 0;
	}
	for (int i = 0; i < n; i++)
	{
		tmp[a[i] - min]++;
	}
	int k = 0;
	for (int i = 0; i < max-min+1; i++)
	{
		while (tmp[i])
		{
			a[k++] = i + min;
			tmp[i]--;
		}
	}
}

void PrintArr(int* a, int n)
{
	for (int i = 0; i < n; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");
}

void MergeSort(int* a, int* tmp, int begin, int end)
{
	if (begin >= end)
		return;
	int mid = (begin + end) / 2;
	MergeSort(a, tmp, begin, mid);
	MergeSort(a, tmp, mid + 1, end);
	int begin1 = begin;
	int begin2 = mid+1;
	int len = 0;
	while (begin1 <= mid && begin2 <= end)
	{
		if (a[begin1] <= a[begin2])
		{
			tmp[len++] = a[begin1++];
		}
		else
		{
			tmp[len++] = a[begin2++];
		}
	}
	while (begin1 <= mid)
	{
		tmp[len++] = a[begin1++];
	}
	while (begin2 <= end)
	{
		tmp[len++] = a[begin2++];
	}
	memcpy(a + begin, tmp, sizeof(int)*(end-begin+1));
}

void MergeSortNonR(int*a ,int n,int* tmp)
{
	int gap = 1;
	while (gap<n)
	{
		for (int i = 0; i < n; i += 2 * gap)
		{
			int begin1 = i, end1 = i + gap - 1;
			int begin2 = i+gap, end2 = i + 2 * gap - 1;
			if (end1 >= n)
			{
				break;
			}
			if (begin2 >= n)
			{
				break;
			}
			if (end2 >= n)
			{
				end2 = n - 1;
			}
			int len = 0;
			while (begin1 <= end1 && begin2 <= end2)
			{
				if (a[begin1] <= a[begin2])
				{
					tmp[len++] = a[begin1++];
				}
				else
				{
					tmp[len++] = a[begin2++];
				}
			}
			while (begin1 <= end1)
			{
				tmp[len++] = a[begin1++];
			}
			while (begin2 <= end2)
			{
				tmp[len++] = a[begin2++];
			}
			memcpy(a + i, tmp, sizeof(int) * (end2 - i + 1));
		}
		gap *= 2;
	}

}

int main()
{
	int arr[11] = { 9,5,6,7,8,9,1,2,3,4 };
	int* tmp = (int*)malloc(11 * sizeof(int));
	//MergeSortNonR(arr, 11, tmp);
    CountSort(arr, 11);
	PrintArr(arr, sizeof(arr) / sizeof(arr[0]));
	
	return 0;
}